<?php

namespace WxWorkSDK\SendMessage\ChatMessage;

use WxWorkSDK\Error\Error;
use WxWorkSDK\Http\Http;
use WxWorkSDK\Result;

abstract class SendBase
{
    const URI = 'appchat/send?access_token=';

    /**
     * @var string
     * @annotation 群聊id
     */
    public $chatId = '';

    /**
     * @var string
     * @annotation
     */
    public $accessToken = '';

    /**
     * @var int
     * @annotation 表示是否是保密消息，0表示否，1表示是，默认0
     */
    public $safe = 0;

    /**
     * @return array
     * @annotation
     */
    abstract public function buildParam(): array;

    /**
     * @return string
     * @annotation 按照规则自定义人数据检测
     */
    abstract public function customCheck(): string;

    /**
     * @param $response
     * @return Result
     * @annotation
     */
    private function respond($response): Result
    {
        $response = json_decode($response, true);
        if ($response['errcode'] == 0) {
            return new Result(true, 0, 'ok');
        } else {
            return new Result(false, Error::WX_MISTAKE, $response['errcode'].':'.$response['errmsg']);
        }
    }

    /**
     * @return string
     * @annotation
     */
    public function check(): string
    {
        if (empty($this->accessToken)) {
            return Error::NOT_TOKEN_MSG;
        }
        if (empty($this->chatId)) {
            return "无群聊id";
        }
        if ($result = $this->customCheck()) {
            return $result;
        }
        return '';
    }

    /**
     * @return Result
     * @annotation
     */
    public function send(): Result
    {
        if ($result = $this->check()) {
            return new Result(false, Error::PARAM_MISTAKE, $result);
        }
        list($bool, $response) = Http::request('POST', self::URI.$this->accessToken, ['json' => $this->buildParam()]);
        if ($bool) {
            return $this->respond($response);
        } else {
            return $response;
        }
    }

}